package com.ybdz.scanner.base;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by gs on 2018/3/20.
 */

public abstract class BaseAdapter<T extends BaseAdapter.BaseViewHolder> extends RecyclerView.Adapter {
    private OnItemClickListener listener;//设置ITEM点击事件

    public final  void setOnItemClickListener(OnItemClickListener listener){
        this.listener=listener;
    }

    @Override
    public final  BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return (BaseViewHolder) CreateChildViewHolder(parent,viewType);
    }

    public abstract T  CreateChildViewHolder(ViewGroup parent, int viewType);



    @Override
    public final  void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof  BaseViewHolder){
            ((BaseViewHolder) holder).setListener(listener);
            ((BaseViewHolder)holder).setPosition(position);
        }
        bindViewHolder((T) holder,position);
    }

    public abstract  void  bindViewHolder(T holder,int position);

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        super.onViewRecycled(holder);
        if (holder instanceof  BaseViewHolder){
            ((BaseViewHolder) holder).clearListener();
        }

    }

    public static  class  BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        private OnItemClickListener listener;

        private int position;

        public BaseViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);

        }

        public void clearListener(){
            listener=null;
        }

        public void setListener(OnItemClickListener listener){
            this.listener=listener;
        }

        public void setPosition(int position){
            this.position=position;
        }

        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onItemClick(v,position);
            }
        }
    }

    public static  interface  OnItemClickListener{
        void onItemClick(View view, int position);
    }
}
